package ee.fj.http;

import java.util.Hashtable;
import java.util.Map;


public class BinderImpl implements BinderParser, Binder {
	private final Map<String, BinderImpl> paths = new Hashtable<String, BinderImpl>();
	private final ResponseHandler handler;
	private final String path;

	public BinderImpl(ResponseHandler handler, String path) {
		this.handler = handler;
		this.path = path;
	}

	@Override
	public final Binder bind(String path, ResponseHandler solver) {
		synchronized (paths) {
			BinderImpl sv = new BinderImpl(solver, path);
			this.paths.put(path, sv);
			return sv;
		}
	}

	@Override
	public final void handle(Request request, Response response) throws Exception {
		if (this.paths.containsKey(request.path)) {
			String[] paths = request.getSubPath();
			String path = Request.DEFAULT_PATH;
			String[] newPaths = null;
			if (paths != null && paths.length > 0) {
				path = paths[0];
				if (paths.length > 1) {
					newPaths = new String[paths.length -1];
					for (int i = 1; i < paths.length; i++) {
						newPaths[i-1] = paths[i];
					}
				} else {
					newPaths = new String[0];
				}
			}
			this.paths.get(request.path).handle(new Request(request, path, newPaths), response);
			return;
		} else {
			this.handler.handle(request, response);
		}
	}

	@Override
	public String getPath() {
		return path;
	}
}
